package io.renren.hd.service.impl;


import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;

import io.renren.hd.dto.DataSourceDTO;
import io.renren.hd.service.ApiDataSourceService;
import io.renren.utils.DataSourceUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import javax.validation.constraints.NotBlank;
import java.util.Set;

/**
 * @author liuzhen
 * @Description: 动态添加数据源,删除数据源
 * @date 2022/1/6 10:52
 */
@Service
public class ApiDataSourceServiceImpl implements ApiDataSourceService {
	@Autowired
	private DataSource dataSource;

	@Autowired
	private DataSourceCreator dataSourceCreator;

	/**
	 * 添加数据源
	 *      //通用数据源会根据maven中配置的连接池根据顺序依次选择。
	 *     //默认的顺序为druid>hikaricp>beecp>dbcp>spring basic
	 * @param dto
	 * @return
	 */
	@Override
	public Set<String> add(DataSourceDTO dto) {
		//测试连接是否正常
		boolean b = DataSourceUtil.testDatasource(dto.getUrl(), dto.getUsername(), dto.getPassword(), dto.getDriverClassName());
		if (!b){
			throw new RuntimeException("连接失败");
		}
		String poolName = dto.getPoolName();
		DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
		Set<String> keySet = ds.getCurrentDataSources().keySet();
		//创建连接
		if (!keySet.contains(poolName)){//如果当前不存在该数据源,那才创建
			DataSourceProperty dataSourceProperty = new DataSourceProperty();
			BeanUtils.copyProperties(dto, dataSourceProperty);
			DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
			ds.addDataSource(dto.getPoolName(), dataSource);
		}
		return ds.getCurrentDataSources().keySet();//返回当前数据源集合
	}


	/**
	 * 查询当前所有数据源
	 * @return
	 */
	@Override
	public Set<String> now() {
		DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
		return ds.getCurrentDataSources().keySet();
	}

	/**
	 * 移除删除数据源
	 * @param name
	 * @return
	 */
	@Override
	public Set<String> remove(String name) {
		DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
		ds.removeDataSource(name);
		return ds.getCurrentDataSources().keySet();
	}
}
